package algorithm.dichotomy.leetcode;

/**
 * @author: 柒月
 * @date: 2025/5/1 下午5:32
 * @version: 1.0
 */
public class Problem81 {

    // https://leetcode.cn/problems/search-in-rotated-sorted-array-ii/
    public boolean search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        if (nums.length == 1) {
            return nums[0] == target;
        }
        if (nums[0] == target) {
            return true;
        }
        int left = 0, right = nums.length - 1, head, tail;
        while (right > left && nums[left] == nums[0]) {
            left++;
        }
        while (right > left && nums[right] == nums[0]) {
            right--;
        }
        head = left;
        tail = right;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                return true;
            } else if (nums[mid] <= nums[tail]) {
                if (target <= nums[tail] && nums[mid] < target) {
                    left = mid + 1;
                }else {
                    right = mid - 1;
                }
            }else {
                if (target >= nums[head] && target < nums[mid]){
                    right = mid - 1;
                }else {
                    left = mid + 1;
                }
            }
        }
        return false;
    }
}
